import base64
import hashlib
import hmac
import json
import os
import time
from hashlib import sha256
import requests
import random
import string
import base64
from Crypto.Cipher import AES
import logging
app_logger = logging.getLogger("student")
from Crypto.Util.Padding import pad

"""
正式环境
appKey
3ab49dd1c2fd47e7be54648e0d8bd98b
appSecret
b2772cc564ec6bc51051e107d65440cb
合同地址
https://contract.gongmall.com/url_contract.html?companyId=zkvAJM&positionId=PL867P
"""

"""
测试环境
名称：杭州摩米文化创意有限公司
appKey
29b2b430391a4a90b2c72cff28de7db5
appSecret
3f8e538747dec4ccbac327caa480a3d8
合同地址
https://contract-qa.gongmall.com/url_contract.html?companyId=P1rvAM&positionId=PXa06M
测试环境：
账户：工猫资金账户测试（默认充值50万元）
"""


host = ""
# 应用ID
appKey = "3ab49dd1c2fd47e7be54648e0d8bd98b"
# 应用密钥
appSecret = "b2772cc564ec6bc51051e107d65440cb"
# 签名
sign = ""
# 随机数，请每次随机产生，保证随机数不可预测
nonce = ""
# 电签合同
urlContract = "https://contract.gongmall.com/url_contract.html?companyId=zkvAJM&positionId=PL867P"


class SignUtil(object):

    @staticmethod
    def getSign(parms):
        p = sorted(parms)
        strs = ""
        for v in p:
            strs += v
            strs += "="
            strs += str(parms[v])
            strs += "&"
        string = strs[0:-1]
        stringSignTemp = "{}&appSecret={}".format(string, appSecret)
        sign = hashlib.md5(stringSignTemp.encode()).hexdigest()
        return sign.upper()

    @staticmethod
    def getCommonData():
        # 当前毫秒时间戳
        timestamp = str(round(time.time() * 1000))
        # 随机数，请每次随机产生，保证随机数不可预测
        common_data = {
            "appKey": appKey,
            "timestamp": timestamp,
            "nonce": ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(30))
        }
        return common_data

    @staticmethod
    def contract(parms):
        string_k = appKey+appSecret
        # 加密key由配置的appKey与appSecret生成
        key = hashlib.md5(string_k.encode()).hexdigest().upper()
        key = base64.b64decode(key.encode())
        strs = ""
        for v in parms:
            strs += v
            strs += "="
            strs += str(parms[v])
            strs += "&"
        string = strs[0:-1]
        raw = pad(string.encode(), 16)
        iv = bytes([0] * 16)
        cipher = AES.new(key, AES.MODE_CBC, iv)
        encrypted_str = cipher.encrypt(raw)
        return urlContract+"&data="+base64.b64encode(encrypted_str).decode('utf-8')